// import { fetchPerson } from '../../../services/usercenter/fetchPerson'
// import { phoneEncryption } from '../../../utils/util'
import Toast from '@vant/weapp/toast/toast'
import Notify from '@vant/weapp/notify/notify'
import { request } from '../../../util'
const api = require('../../../api')
import Dialog from '@vant/weapp/dialog/dialog'

Page({
  data: {
    userInfo: {},
    formdata: {},
    showUnbindConfirm: false,
    display: 'none',
    display2: 'inline-black',
    seconds: 59,
    defaultAvatarUrl: 'http://localhost:8021/img/avatar_url/icon-user-center-avatar@2x.png',
    pickerOptions: [
      {
        name: '男',
        code: '1'
      },
      {
        name: '女',
        code: '2'
      }
    ],
    properties: {
      userInfo: {
        type: Object,
        value: {},
        observer(vale) {
          console.log(vale)
        }
      }
    },
    typeVisible: false,
    typeVisible2: false,
    genderMap: ['', '男', '女']
  },
  onLoad(options) {
    this.setData({
      userInfo: JSON.parse(options.userInfo)
    })
    console.log(this.data.userInfo)
    //this.init();
  },
  onShow() {
    // this.setData({
    //   userInfo: wx.getStorageSync('userInfo'),
    // });
    this.fetUseriInfoHandle()
  },
  fetUseriInfoHandle() {
    console.log()
    var ok = false
    if (Object.keys(wx.getStorageSync('userInfo')).length > 0) {
      ok = true
    }
    this.setData({
      userInfo: ok ? wx.getStorageSync('userInfo') : {},
      currAuthStep: ok ? 2 : 1
    })
  },
  init() {
    //this.fetchData()
  },
  // fetchData() {
  //   fetchPerson().then(personInfo => {
  //     this.setData({
  //       personInfo,
  //       'personInfo.phoneNumber': phoneEncryption(personInfo.phoneNumber)
  //     })
  //   })
  // },
  onClickCell({ currentTarget }) {
    this.setData({
      typeVisible: true
    })
    // console.log(currentTarget);
    // const { dataset } = currentTarget;
    // const { nickName } = this.data.userInfo.name;
    // switch (dataset.type) {
    //   case 'sex':
    //     this.setData({
    //       typeVisible: true,
    //     });
    //     break;
    //   case 'name':
    //     // this.setData({
    //     //   typeVisible2: true,
    //     // });
    //     wx.navigateTo({
    //       url: `/pages/usercenter/name-edit/index?phone=${nickName}`,
    //     });
    //     break;
    //   case 'phone':
    //     this.toModifyAvatar();
    //     break;
    //   default: {
    //     break;
    //   }
    // }
  },
  updateName() {
    wx.navigateTo({
      url:
        `/pages/user-center/name-edit/index?name=${this.data.userInfo.name}` +
        '&isname=true&isphone=false&id=' +
        this.data.userInfo.id
    })
  },
  updatePhone() {
    wx.navigateTo({
      url:
        `/pages/user-center/name-edit/index?phone=${this.data.userInfo.phone}` +
        '&isname=false&isphone=true&id=' +
        this.data.userInfo.id
    })
  },
  openUnbindConfirm() {
    Dialog.confirm({
      title: '退出',
      message: '是否退出登录'
    })
      .then(() => {
        // on confirm
        //清除缓存
        wx.removeStorageSync('userInfo')
        wx.removeStorageSync('token')
        //跳转页面
        wx.redirectTo({ url: '/pages/usercenter/index?currAuthStep=1' })
      })
      .catch(() => {
        // on cancel
      })
  },
  onClose() {
    this.setData({
      typeVisible: false
    })
  },
  onConfirm(e) {
    const { value } = e.detail
    var that = this
    request(api.updateUser, { id: that.data.userInfo.id, sex: value }, 'post').then(function (res) {
      if (res.code == 200) {
        Toast({
          context: that,
          selector: '#t-toast',
          message: '设置成功',
          theme: 'success'
        })
        that.setData({
          typeVisible: false,
          'userInfo.sex': value
        })
        console.log(that.data.userInfo)
        wx.setStorageSync('userInfo', that.data.userInfo)
        console.log(wx.getStorageSync('userInfo'))
      } else {
        Notify({ type: 'danger', message: res.msg })
      }
    })
  },
  // 确认点击头像
  onChooseAvatar(e) {
    console.log(e)
    var that = this
    wx.downloadFile({
      url: e.detail.avatarUrl,
      success(res) {
        console.log(res)
        wx.uploadFile({
          filePath: res.tempFilePath,
          name: 'file',
          url: api.uplodefile,
          header: {
            'Content-Type': 'multipart/form-data',
            'X-Litemall-id': wx.getStorageSync('userInfo').id
          },
          success: function (res) {
            console.log(res)
            var data = JSON.parse(res.data)
            console.log(data)
            if (data.code == 200) {
              Notify({ type: 'success', message: '修改成功' })
              that.setData({
                'userInfo.avatarUrl': data.data.path
              })
              console.log(that.data.userInfo)
              wx.setStorageSync('userInfo', that.data.userInfo)
            } else {
              Notify({ type: 'danger', message: data.msg })
            }
          }
        })
      }
    })
  },
  onChange(e) {
    console.log(e)
    this.setData({
      'formdata.name': e.detail.trim()
    })
  },
  onChange2(e) {
    this.setData({
      'formdata.phone': e.detail.trim()
    })
  },
  onChange3(e) {
    this.setData({
      'formdata.yzmcode': e.detail.trim()
    })
  },
  sureMsg(e) {
    var that = this
    if (
      this.data.formdata.name == null ||
      this.data.formdata.name.trim() == '' ||
      this.data.formdata.name == undefined
    ) {
      Notify({ type: 'danger', message: '请确保内容完整' })
      return false
    }
    if (
      this.data.formdata.phone == null ||
      this.data.formdata.phone.trim() == '' ||
      this.data.formdata.phone == undefined
    ) {
      Notify({ type: 'danger', message: '请确保内容完整' })
      return false
    }

    if (
      this.data.formdata.yzmcode == null ||
      this.data.formdata.yzmcode.trim() == '' ||
      this.data.formdata.yzmcode == undefined
    ) {
      Notify({ type: 'danger', message: '请输入验证码' })
      return false
    }
    this.setData({
      'formdata.id': this.data.userInfo.id
    })
    console.log(this.data.formdata)
    request(api.updateUser, this.data.formdata, 'post').then(function (res) {
      console.log(res)
      if (res.code == 200) {
        Notify({ type: 'success', message: '修改成功' })
        that.setData({
          'userInfo.name': that.data.formdata.name,
          'userInfo.phone': that.data.formdata.phone
        })
        wx.setStorageSync('userInfo', that.data.userInfo)
      } else {
        Notify({ type: 'danger', message: res.msg })
      }
    })
  },

  timeChange(e) {
    //倒计时改变
    this.setData({
      seconds: e.detail.seconds
    })
  },
  timeFinish(e) {
    //倒计时结束
    const countDown = this.selectComponent('.control-count-down')
    countDown.reset()
    this.setData({
      display: 'none',
      display2: 'inline-black'
    })
  },
  //获取验证码
  getYzm() {
    var that = this
    if (
      this.data.formdata.phone == null ||
      this.data.formdata.phone.trim() == '' ||
      this.data.formdata.phone == undefined
    ) {
      Notify({ type: 'danger', message: '请填写手机号' })
      return false
    }

    request(api.smsyzm + '?phone=' + this.data.formdata.phone, {}, 'post').then(function (res) {
      console.log(res)
      if (res.code == 200) {
        Notify({ type: 'success', message: '发送成功' })
        that.setData({
          display: 'inline-black',
          display2: 'none'
        })
        const countDown = that.selectComponent('.control-count-down')
        countDown.start()
      } else {
        Notify({ type: 'danger', message: res.msg })
      }
    })
  }
  // async toModifyAvatar() {
  //   try {
  //     const tempFilePath = await new Promise((resolve, reject) => {
  //       wx.chooseImage({
  //         count: 1,
  //         sizeType: ['compressed'],
  //         sourceType: ['album', 'camera'],
  //         success: (res) => {
  //           const { path, size } = res.tempFiles[0];
  //           if (size <= 10485760) {
  //             resolve(path);
  //           } else {
  //             reject({ errMsg: '图片大小超出限制，请重新上传' });
  //           }
  //         },
  //         fail: (err) => reject(err),
  //       });
  //     });
  //     const tempUrlArr = tempFilePath.split('/');
  //     const tempFileName = tempUrlArr[tempUrlArr.length - 1];
  //     Toast({
  //       context: this,
  //       selector: '#t-toast',
  //       message: `已选择图片-${tempFileName}`,
  //       theme: 'success',
  //     });
  //   } catch (error) {
  //     if (error.errMsg === 'chooseImage:fail cancel') return;
  //     Toast({
  //       context: this,
  //       selector: '#t-toast',
  //       message: error.errMsg || error.msg || '修改头像出错了',
  //       theme: 'error',
  //     });
  //   }
  // },
})
